<template>
  <div class="home">
    <h2>02_pinia的state定义_读取_写入_改变_替换</h2>
    <h2>name: {{ useUserStore.name }}</h2>
    <h2>age: {{ age }}</h2>
    <h2>height: {{ height }}</h2>
    <button @click="changeState">逐个改state</button>
    <button @click="changeStateOne">一次性修改state</button>
    <button @click="resetState">重置state</button>
    <button @click="replaceState">替换state</button>
  </div>
</template>

<script setup>
  import useUser from '@/stores/user'
  import { toRefs } from 'vue'
  import { storeToRefs } from 'pinia' 

  const useUserStore = useUser()

  const { name, age, height } = storeToRefs(useUserStore)

  // 读取,写入state
  function changeState() {
    // 通过 store 实例访问状态来直接读取和写入状态
    // 逐个修改 
    useUserStore.name = 'kobe'
    useUserStore.age++
    useUserStore.height = 2.00
  }

  function changeStateOne() {
    // 一次性修改多个状态
    useUserStore.$patch({ // 传入对象或者函数
      name: 'james',
      age: 20,
      height: 1.98
    })
  }

  // 重置state
  function resetState() {
    // 调用 store 上的 $reset() 方法将状态 重置 到其初始值
    useUserStore.$reset()
  }
  
  // 替换state, 替换state为新对象
  const oldState = useUserStore.$state // 旧state
  console.log(oldState)
  function replaceState() {
    useUserStore.$state = {
      name: 'curry',
      age: 30,
      // height: 1.80
    }
    console.log(oldState === useUserStore.$state) // 旧state
  }
  console.log(useUserStore.$state) // 新state

</script>

<style scoped>
</style>